namespace SB2.Core;

public static class SBServe
{
    // 初始化数据库
    public static async void InitDb()
    {
        var db = App.GetService<SysVersionRepository>();
        db.Init();
        var lastversion = await db.GetLastVersion();
        Console.WriteLine(lastversion);
        // list.ForEach(m => { Console.WriteLine(m); });
        App.Assemblies
        .Where(m => m.FullName.StartsWith("SB"))
        .SelectMany(m => m.GetManifestResourceNames()
            .Where(n => n.ToLower().EndsWith(".sql"))
            .Select(n =>
            {
                // Console.WriteLine(n);
                using (var reader = new System.IO.StreamReader(m.GetManifestResourceStream(n)))
                {
                    return new
                    {
                        name = long.Parse(n.ToLower().Replace(".sql", "").Split('.').Last()),
                        sql = reader.ReadToEnd()
                    };
                }
            }))
.Where(m => m.name > lastversion && (!string.IsNullOrEmpty(m.sql)))
.OrderBy(m => m.name)
.ToList().ForEach(async m =>
{
    Console.WriteLine($"更新数据库脚本：{m.name}");
    if (!await db.UpdateVersion(m.sql, m.name))
        throw new Exception("脚本执行失败。");
});


    }

}